import { getSiteNum } from '@/api/manage/info'

export const setSearchParams = function(params,page_size,page,order,sort){
  let searchParams = {
    filter:{},
    op:{},
  }
  for(let item in params){
    let value = params[item].value
    if(value){
      searchParams.filter[item] = value
      if(params[item].op){
        searchParams.op[item]= params[item].op
      } else {
        searchParams.op[item]= '='
      }
    }
    
  }
  if(page_size){
    searchParams.page_size = page_size
  }

  if(page){
    searchParams.page = page
  }

  if(order){
    searchParams.order = order
  }

  if(sort){
    searchParams.sort = sort
  }
  return searchParams
}


export  const  appendStatus = function(list){
  for(let item in list){
    if(list[item].status =="normal"){
      list[item].statusBoolean = true
    }else{
      list[item].statusBoolean = false
    }
    if(list[item].childlist && list[item].childlist.length>0){
      appendStatus(list[item].childlist)
    }
  }
  return list
}

export  const setErrorTip = function(res){
  let word = ''
  if(res.message){
    word += res.message
  } 
  if(res.data && res.data.length > 0){
    word += JSON.stringify(res.data)
  }
  return word
}


export  const extendObj = function  () {
  var length = arguments.length
  var target = arguments[0] || {}
  if (typeof target !== 'object' && typeof target !== 'function') {
    target = {}
  }
  var i = 1
  if (length === 1) {
    target = this
    i--
  }
  for (i; i < length; i++) {
    var source = arguments[i]
    for (var key in source) {
      // 使用for in会遍历数组所有的可枚举属性，包括原型。
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        target[key] = source[key]
      }
    }
  }
  return target
}

export const hasPermission = userPermission => {
  // 当前按钮列表，我是用本地缓存存储
  let btnPermissionList = JSON.parse(localStorage.getItem('permission'))
  // 因为后台返回的不是以按钮名的数组，所以需要过滤
  let eglishPermission = btnPermissionList.map((v) => {
      return v
  })
  // 是否在权限数组里面
  let status = eglishPermission.includes(userPermission)
  return status
}

export const setTabWidth = function (){
  getSiteNum().then(res=>{
    let width = 100 / res + '%'
    document.getElementsByTagName('body')[0].style.setProperty('--site-length', width)
  })

}


export const timeFormat = function(date) {
  let year = date.getFullYear() 
  let month = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : '0'+(date.getMonth() + 1)
  let day = date.getDate() >= 10 ? date.getDate(): '0' + date.getDate()
  let hour = date.getHours() >=10 ? date.getHours() : '0' + date.getHours() 
  let minute = date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes() 
  let second = date.getSeconds() >= 10 ? date.getSeconds(): '0' + date.getSeconds()
  let str = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  return str
}

Date.prototype.Format = function (fmt) {
  var o = {
      "M+": this.getMonth() + 1, //月份 
      "d+": this.getDate(), //日 
      "H+": this.getHours(), //小时 
      "m+": this.getMinutes(), //分 
      "s+": this.getSeconds(), //秒 
      "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
      "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)){
      fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o){
       if (new RegExp("(" + k + ")").test(fmt)){
           fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));    
       }
  }
  return fmt;
}

export const timeTransfor = function (arr, cycle) {
  let obj = {
    start_date:'',
    end_date: '',
  }
  let start_date_year = parseInt(arr[0].split('-')[0]) 
  let start_date_month = parseInt(arr[0].split('-')[1]) 
  let end_date_year = parseInt(arr[1].split('-')[0]) 
  let end_date_month = parseInt(arr[1].split('-')[1]) 

  if(cycle == '日') {
    obj.start_date = arr[0]
    obj.end_date = arr[1]
  } else if (cycle == '月') {
    obj.start_date = new Date(start_date_year, start_date_month-1).Format('yyyy-MM-dd')
    obj.end_date = new Date(end_date_year, end_date_month, 0).Format('yyyy-MM-dd')
  } else if (cycle == '季' ) {
    let start_quarter = 1
    if(start_date_month >= 1 && start_date_month <= 3) {
      start_quarter = 1
    } else if(start_date_month >= 4 && start_date_month <= 6){
      start_quarter = 4
    } else if(start_date_month >= 7 && start_date_month <= 9){
      start_quarter = 7
    } else if(start_date_month >= 10 && start_date_month <= 12){
      start_quarter = 9
    }
    let end_quarter = 3
    if(end_date_month >= 1 && end_date_month <= 3) {
      end_quarter = 3
    } else if(end_date_month >= 4 && end_date_month <= 6){
      end_quarter = 6
    } else if(end_date_month >= 7 && end_date_month <= 9){
      end_quarter = 9
    } else if(end_date_month >= 10 && end_date_month <= 12){
      end_quarter = 12
    }
    obj.start_date = new Date(start_date_year, start_quarter-1).Format('yyyy-MM-dd')
    obj.end_date = new Date(end_date_year, end_quarter, 0).Format('yyyy-MM-dd')
  } else if (cycle == '年' ) {
    obj.start_date = new Date(start_date_year, 0).Format('yyyy-MM-dd')
    obj.end_date = new Date(end_date_year, 12, 0).Format('yyyy-MM-dd')
  }
  return obj
}


export const setEchartsOptionsDatazoom  = function (cycle, xAxis) {
  let maxValueSpan = 12
  if(cycle == '年') {
    maxValueSpan = 4
  } else if(cycle == '季') {
    maxValueSpan = 8
  } else if(cycle == '时') {
    maxValueSpan = 24
  }
  let len = xAxis.length
  let end = len - 1
  let start = len - maxValueSpan 
 

   // 堆叠图柱状图
   let dataZoom = [
    // { // 滚动缩放
    //   type: 'inside',
    //   maxValueSpan: maxValueSpan
    // },
    {
      type: 'slider',
      show: true,//显示滚动条
      zoomLock:false,//锁定滚动条缩放，（固定滚动条长度）
      // xAxisIndex: [0],
      left: '0%',//离左边的百分比距离
      right: 0,
      bottom: 0,
      borderColor: "#f3f3f3",//边框和背景颜色一致，（因为无法做到无边框，只能跟随页面背景）
      height: 11,//滚动条高度
      showDetail: false,//关闭：拖拽时候显示详细数值信息。
      fillerColor: '#cccccc',//滚动条颜色
      handleSize: '100%',//矢量尺寸占比
      endValue: end,
      startValue: start,
      rangeMode: 'value', //value时使用endValue,startValue
      dataBackground:{
        areaStyle: {
          color: '#ebeaea',
        }
      },
      handleStyle: {
        borderWidth: 0,
        color: '#fffFFf',
        shadowColor: 'rgba(0, 0, 0, 0.1)',
        shadowBlur: 5
      },//SVG图形填充颜色
      handleIcon: "path://M512,512m-448,0a448,448,0,1,0,896,0a448,448,0,1,0,-896,0Z",//直接画一个圆形SVG矢量路径
    }
  ]
  return dataZoom
}

export const setEchartsBarwidth  = function (obj,cycle, len ) {
  if(cycle == '年' ) {
    if(len == 1) {
      obj.barWidth = '15%';
    }else if(len == 2) {
      obj.barWidth = '18%';
    } else if(len == 3) {
      obj.barWidth = '20%';
    } else if(len >= 4 ) {
      obj.barWidth = '22%';
    }
  
  } else if(cycle == '月' || cycle == '日' ) {
    if(len == 1) {
      obj.barWidth = '15%';
    }else if(len == 2) {
      obj.barWidth = '15%';
    } else if(len == 3) {
      obj.barWidth = '20%';
    } else if(len == 4) {
      obj.barWidth = '22%';
    } else if(len == 5) {
      obj.barWidth = '24%';
    } else if(len == 6) {
      obj.barWidth = '26%';
    } else if(len == 7) {
      obj.barWidth = '32%';
    } else if(len == 8) {
      obj.barWidth = '36%';
    } else if(len == 9) {
      obj.barWidth = '40%';
    } else if(len == 10) {
      obj.barWidth = '44%';
    } else if(len == 11) {
      obj.barWidth = '50%';
    } else if(len >= 12) {
      obj.barWidth = '55%';
    }
  } else if(cycle == '季') {
     if(len == 1) {
      obj.barWidth = '10%';
    }else if(len == 2) {
      obj.barWidth = '15%';
    } else if(len == 3) {
      obj.barWidth = '20%';
    } else if(len == 4) {
      obj.barWidth = '22%';
    } else if(len == 5) {
      obj.barWidth = '24%';
    } else if(len == 6) {
      obj.barWidth = '26%';
    } else if(len == 7) {
      obj.barWidth = '32%';
    } else if(len >= 8) {
      obj.barWidth = '36%';
    }
  }
  return obj
}
export const transforTime = function(data, cycle) {
  let array = []
  for (let i = 0; i < data.length; i++) {
    let obj = data[i].split('-')
    let str = ''
    if(cycle === '月') {
      str = obj[0] + '/' + obj[1]
    }else if(cycle === '年') { 
      str = obj[0]
    } else if(cycle ==='季') {
      str =  obj[0]
    } else if (cycle === '日') {
      str = obj[1] + '/' + obj[2]
    } else if (cycle === '时') {
      str = data[i].split(' ')[1] +":00"
    } 
    array.push(str)
  }
  return array

}

export const  setEchartsTooltip = function(axisPointer, isSum, formatter) {
  let axisPointerT = {}
  if(axisPointer === 0) {
    axisPointerT = {            // 坐标轴指示器，坐标轴触发有效
      type: 'shadow',        // 默认为直线，可选为：'line' | 'shadow'
    }
  } else if (axisPointer === 1){
    axisPointerT =  {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      },
      crossStyle: {
        color: '#cccccc',
        type : 'solid'
      },
      snap: true
    }
  }
  let tooltip = {
    trigger: 'axis',
    axisPointer: axisPointerT,
    backgroundColor: 'rgba(255, 255, 255, 0.8)',
    padding: [16, 16, 16, 16], // 提示框浮层内边距
    textStyle: {
      color: '#303030',
      fontSize: 12,
      height: 42,
      width: '100%'
    },
    position: function (pos, params, dom, rect, size) {// pos 鼠标的位置
      // 左右跟随鼠标 距离顶部60 
      var obj = {top: 60};
      let xView = size.viewSize[0]
      if(xView - pos[0] < 200) { // 避免到右边 弹窗被遮挡的情况
        obj.right = xView - pos[0]
      } else{
        obj.left = pos[0]
      }
      return obj;
    },
    formatter: (params) =>{
      let str = ''
      let sum = 0
      if(!formatter) {
        for(let i = 0; i < params.length; i++) {
          sum += parseInt(params[i].data)
          let seriesName = params[i].seriesName.indexOf('率') > -1
          if(seriesName) {
            str += '<p style="width:100px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
            + '<span>' +params[i].marker + ' ' + params[i].seriesName + '</span><span >' + params[i].data  + '%</span> '+ '</p>' 
          
          } else {
            str += '<p style="width:100px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
            + '<span>' +params[i].marker + ' ' + params[i].seriesName + '</span><span >' + params[i].data  + '</span> '+ '</p>'   
          }
        }
      } else if (formatter === 1) { // 产品转换率图表 
        for(let i = 0; i < params.length; i++) {
          str += '<p style="width:180px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
          + '<span>点击Amazon的数量</span><span >' + params[i].data.amazon_button_num  + '</span> '+ '</p>' +
          '<p style="width:180px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
          + '<span>浏览量</span><span >' + params[i].data.page_view  + '</span> '+ '</p>' 
          let seriesName = params[i].seriesName.indexOf('率') > -1
          if(seriesName) {
            str +='<p style="width:180px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
            + '<span>' + params[i].seriesName + '</span><span >' + params[i].data.rate  + '%</span> '+ '</p>'   
          } else {
            str +='<p style="width:180px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
            + '<span>' + params[i].seriesName + '</span><span >' + params[i].data.rate  + '</span> '+ '</p>'  
          }
      }
      }else if (formatter === 2) { // betaTester W到B转换率
        for(let i = 0; i < params.length; i++) {
         
          str += '<p style="width:180px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
          + '<span>W到B的注册成功用户</span><span >' + params[i].data.warranty_register_first_successfully_num  + '</span> '+ '</p>' +
          '<p style="width:180px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
          + '<span>W注册成功量</span><span >' + params[i].data.registered_successfully_num  + '</span> '+ '</p>' 
          let seriesName = params[i].seriesName.indexOf('率') > -1
          if(seriesName > -1) {
            str +='<p style="width:180px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
            + '<span>' + params[i].seriesName + '</span><span >' + params[i].data.rate  + '%</span> '+ '</p>'
          } else {
            str +='<p style="width:180px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
            + '<span>' + params[i].seriesName + '</span><span >' + params[i].data.rate  + '</span> '+ '</p>'
          }
        
        }
      } else if (formatter === 3){ // warranty 销量/注册率
        for(let i = 0; i < params.length; i++) {
          if(params[i].data.registered_successfully_num >= 0) {
            str += '<p style="width:100px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
            + '<span>W注册成功量</span><span >' + params[i].data.registered_successfully_num  + '</span> '+ '</p>'
          }
          let seriesName = params[i].seriesName.indexOf('率') > -1
          if(seriesName) {
            str +='<p style="width:100px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
            + '<span>' + params[i].seriesName + '</span><span >' + params[i].value  + '%</span> '+ '</p>'
          } else {
            str +='<p style="width:100px;height: 25px;display:flex;align-items:center;justify-content: space-between;">' 
            + '<span>' + params[i].seriesName + '</span><span >' + params[i].value  + '</span> '+ '</p>'
          }
        }
      }

      let strF = ''
      if(isSum) {
        strF = '<p style="width:100px;height: 25px;display:flex;align-items:center;justify-content: space-between;">'
        + '<span>' + params[0].axisValue + '</span><span style="margin-left: 15px">' + sum  + '</span> '+ '</p>'
      }else {
        strF = '<p style="width:100px;height: 25px;display:flex;align-items:center;justify-content: space-between;">'
        + '<span>' + params[0].axisValue + '</span><span style="margin-left: 15px"></span> '+ '</p>'
      }
      return strF+str
      // return setEchartsTooltipFormat(params, true)
    }
  }
  return tooltip
}

// 时间范围选择器的配置
export const  setPickerOptions = function() {
  let pickerOptions =  {
    disabledDate: (time) => { //不能选择超过今天的数据
      let date = new Date(Date.now())
      let disabledDate = new Date (date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59)
      return time.getTime() > disabledDate.getTime()
    }
  }
  return pickerOptions

}



export const checkFile = function(fileUrl,type, fileType) {
  let  index = fileUrl.indexOf("."); //（考虑严谨用lastIndexOf(".")得到）得到"."在第几位
  let fileValueSuffix = fileUrl.substring(index); //截断"."之前的，得到后缀
  let patttern = new RegExp('(.*).('+fileType+')$', 'i')
  if(type == 'video') {
      if (!patttern.test(fileValueSuffix)) { //根据后缀，判断是否符合视频格式
          return false;
      }
  }
  if(type == 'image') {
      if (!patttern.test(fileValueSuffix)) { //根据后缀，判断是否符合图片格式
          return false;
      }
  }

  return true;

}

 
// 'MP4|MPEG|AVI|nAVI|ASF|MOV|3GP|WMV|DivX|XviD|RM|RMVB|FLV|F4V' video

// 文件地址补全
export const fileDomain = function() {
  return window.location.protocol+'//' + window.location.hostname+'/file';
}




export const formatFileSize = function(size) {
  let value = Number(size);
  if (size && !isNaN(value)) {
      const units = [ 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB', 'BB'];
      let index = 0;
      let k = value;
      if (value >= 1024) {
          while (k > 1024) {
              k = k / 1024;
              index++;
          }
      }
      return `${(k).toFixed(2)}${units[index]}`;
  }
  return '-';
}


var  utils  = {
  setCdnUrl: function(){
    let hostname = window.location.hostname
    let url = 'bonoch-test'
    if(hostname == 'admin.bonoch.com') {
      url = 'bonoch-line'
    }
    return 'https://'+url+'.oss-us-west-1.aliyuncs.com'
  
  
  },
}
export default utils;

